var $ = null;
var currentWindowWidth = null;
var $form = null;
var playerImages = new Array();
var str = [" ", "é", "í", "ó", "á", "ý", "ú"];
var rep = ["-", "e", "i", "o", "a", "y", "u"];

jQuery(function() {
   $ = jQuery;
   
   currentWindowWidth = $(window).width();

   $form = $("#findBootsByPlayer");
   var $button = $form.find('[type=button]');

   $button.on("click", findBootByPlayer);
   
   $( "#slider-range-max" ).slider({
	range: "max",
	min: 100,
	max: 1000,
	value: 1000,
	slide: function( event, ui ) {
		$( "#amount" ).val( "(" + ui.value  + " kr." + ")");
		}
	});
	$( "#amount" ).val( "(" + $( "#slider-range-max" ).slider( "value" ) + " kr." + ")");

  	$("#boot-button").on("click", function() {

  		$("#results .boot").not(".hide").addClass("hide");

  		$("#results #no-boot-match").hide();

  		var bootMatches = new Array();

  		priceVal = parseInt($("#amount").val().match(/\d+/)[0]);
  	
  		var materials = $('input[name=material_checkbox]:checked').map(function(_, el) {
		    return $(el).attr('id').toLowerCase();
		}).get();

	  	$("#results .boot").each(function(i) {
	  		if($("#select-playertype option:selected").text().toLowerCase() === $(this)[0].getAttribute('data-playertype') || $("#select-playertype option:selected").val() === "") {
	  			if($("#select-foottype option:selected").text().toLowerCase() === $(this)[0].getAttribute('data-foottype') || $("#select-foottype option:selected").val() === "") {
	  				if($("#select-surface option:selected").text().toLowerCase() === $(this)[0].getAttribute('data-surface') || $("#select-surface option:selected").val() === "") {
	  					var str = $(this)[0].getAttribute('data-material');
	  					var strSplit = str.split(", ");
		  				if(checkForMatches(strSplit, materials) || materials.length === 0) {
	  						if(priceVal >= parseInt($(this)[0].getAttribute('data-price'))) {
	  							if($("#select-level option:selected").text().toLowerCase() === $(this)[0].getAttribute('data-level') || $("#select-level option:selected").val() === "") {
	  								if($("#select-brand option:selected").text().toLowerCase() === $(this)[0].getAttribute('data-brand') || $("#select-brand option:selected").val() === "") {
	  									bootMatches.push($(this));
	  								}
	  								else {
	  									return true;
	  								}
	  							}
	  							else {
	  								return true;
	  							}
	  						}
	  						else {
	  							return true;
	  						}
	  					}
	  					else {
	  						return true;
	  					}
	  				}
	  				else {
	  					return true;
	  				}
	  			}
	  			else {
	  				return true;
	  			}
	  		}
	  		else {
	  			return true;
	  		}
	  	});
		for(var i in bootMatches) {
			$(bootMatches[i]).removeClass("hide");
		}
		if(bootMatches.length == 0) {
			$("#no-boot-match").show();
		}

  	});
});

function findBootByPlayer(e)
{
   var searchString = e != undefined ? $($(e.target).parent('form').find('input[type=search]')).val().toLowerCase() : 'n';
   //alert(searchString);
   var matches = new Array();

   for(var i in playersBoots)
   {
      if(playersBoots[i].post_title.toLowerCase().indexOf(searchString) > -1)      
         matches.push(playersBoots[i]);
   }
   renderResults(matches);
}

function renderResults(m)
{
	if(m.length > 0) {
		var $resultWrapper = $('#results');
			$resultWrapper.empty();

		for(i in m)
		{
			var $bootWrapper = $('<div class="boot"></div>');
            $resultWrapper.append($bootWrapper);
			var newBootImage = document.createElement("img");
            newBootImage.src = m[i].bootThumbnail;
			$bootWrapper.append(newBootImage);
			$bootWrapper.append('<span>' + m[i].bootBrand + ' ' + m[i].boot + '</span>');
			var $buttonWrapper = $('<div class="best-price-buttons clearfix"></div>');
			$bootWrapper.append($buttonWrapper);
			$buttonWrapper.append('<a class="best-price-btn" href="' + m[i].bootPageUrl + '">Se priser</a>');
			$buttonWrapper.append('<a class="best-price-btn" href="' + m[i].bestPriceLink + '">Køb nu</a>');

			var newPlayerImage = document.createElement("img");
            newPlayerImage.src = m[i].playerThumbnail;
			$bootWrapper.append(newPlayerImage);
			$bootWrapper.append('<span>' + m[i].post_title + '</span>');

			var replacerClub = m[i].club.replaceArray(str, rep);
			var replacerNation = m[i].nation.replaceArray(str, rep);

			var $uList = $('<ul class="player-info-list"></ul>');
			$bootWrapper.append($uList);
			$uList.append('<li class="' + replacerClub.toLowerCase() + '">' + m[i].club + '</li>');
			$uList.append('<li class="position">' + m[i].position + '</li>');
			$uList.append('<li class="' + replacerNation.toLowerCase() + '">' + m[i].nation + '</li>');
			$uList.append('<li class="foot">' + m[i].foot + '</li>');
			$uList.append('<li class="age">' + m[i].age + ' år</li>');

			if($.map(m[i].clubHistory, function(n, i) { return i; }).length > 0) {			
				var $historyWrapper = $('<table id="player-history"><thead><tr><th>År</th><th>Klub</th><th>Kampe</th><th>Mål</th></tr></thead></table>');
				$bootWrapper.append($historyWrapper);
				var $historytBody = $('<tbody></tbody>');
				$historyWrapper.append($historytBody);
				var history = m[i].clubHistory;

				for(index in history)
				{
					var strSplit = history[index].split("|");
					var $tr = $('<tr></tr>');
					$historytBody.append($tr);
					for(i in strSplit) {
						$tr.append('<td>' + strSplit[i] + '</td>');
					}
				}
			}
		}
	}
}


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

function checkForMatches(myArray, arrayMatch) {
    var i, j;
    var totalmatches = 0;
    for (i = 0; i < myArray.length; i++) {
        for (j = 0; j < arrayMatch.length; ++j) {
            if (myArray[i] == arrayMatch[j]) {

                totalmatches++;

            }

        }
    }
    if (totalmatches > 0) {
        return true;
    } else {
        return false;
    }
}

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  for (var i = 0; i < find.length; i++) {
    replaceString = replaceString.replace(find[i], replace[i]);
  }
  return replaceString;
};